﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Caching;
using System.Collections;
using System.Reflection;
using System.IO;

namespace BulldogCMS.Core.MVC
{
    public class VirtualFileProvider : VirtualPathProvider
    {
        public VirtualFileProvider() { }

        // ~/BulldogCMS.Web/Views/About/Index.cshtml
        public override bool FileExists(string virtualPath) {
            if (Context.ResourceFilesHelper.IsModuleActive())
            {
                return Context.ResourceFilesHelper.FileExistsInCurrentModule(virtualPath);
            }
            return base.FileExists(virtualPath) || Context.ResourceFilesHelper.FileExists(virtualPath);
        }

        public override VirtualFile GetFile(string virtualPath) {
            if (Context.ResourceFilesHelper.IsModuleActive())
            {
                if (Context.ResourceFilesHelper.FileExistsInCurrentModule(virtualPath))
                {
                    return new ModuleResourceVirtualFile(Context.ResourceFilesHelper.GetModuleResourceStream(virtualPath), virtualPath);
                }
                throw new ApplicationException("File not found in current active module");
            }
            else if (base.FileExists(virtualPath))
            {
                return base.GetFile(virtualPath);
            }
            else
            {
                return new ResourceVirtualFile(virtualPath);
            }
        }

        public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { if (Context.ResourceFilesHelper.FileExists(virtualPath)) { return null; } else { return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart); } }

    }
}